package com.lrj.wc;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author lrj
 * @date 2022/3/18 15:34
 */
public class ParameterToolWordCount {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        ParameterTool parameterTool = ParameterTool.fromArgs(args);
        // Command Args: --host xxx --port xxx
        final SingleOutputStreamOperator<Tuple2<String, Long>> sum = env.socketTextStream(parameterTool.get("host"), parameterTool.getInt("port",999))
                .flatMap((String s, Collector<Tuple2<String, Long>> c) -> {
                    for (String str : s.split("\\s+")) {
                        c.collect(new Tuple2<>(str, 1L));
                    }
                }).returns(Types.TUPLE(Types.STRING, Types.LONG))
                .keyBy(v -> v.f0)
                .sum(1);
        sum.print();
        env.execute(StreamWordCount.class.getName());
    }
}
